<?php

namespace App\Module\Api\Controllers;
use App\Exceptions\Customize\ParamsException;
use App\Module\Api\Controllers\Request\RepeatedEliminationRequest;
use App\Module\Api\Validator\RepeatedEliminationValidator;
use App\System\Base\Services\TokenService;
use App\System\Cis\Repositories\CisUserRepository;
use App\System\Coupon\Repositories\CouponUserRepository;
use App\System\Fina\Repositories\FinaIntegralRegRecordRepository;
use App\System\Log\Repositories\LogRepeatedEliminationRepository;
use Illuminate\Support\Facades\DB;

/**
 * 复销
 */
class RepeatedEliminationController extends Controller
{
    public function __construct()
    {
        $this->query = new RepeatedEliminationRequest();
        parent::__construct();
    }

    public function index()
    {
        (new RepeatedEliminationValidator())->check();
        $master_id = TokenService::getMasterId();
        $user_id = TokenService::getUserId();
        DB::beginTransaction();
        $user = CisUserRepository::getInstance();
        $master_info = $user->checkPayPassword($master_id,$this->query->payPassword);
        if(!$master_info)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '支付密码错误',
            ]);
        }
        $user_info = $user->getUser($user_id);

        if($user_info->repeated_consumption_date)
        {//有复销日期，即已发过工资的才执行复销业务
            if($user_info->integral < 1000)
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '复消失败，积分不足1000',
                ]);
            }
            $res = $user->updateUserPurse($user_id,2,'integral',1000);//先扣钱
            if(!$res)
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '复消失败，扣款失败',
                ]);
            }
            $fina_set = ['income'=>2,
                         'type'=>13,
                         'record_type'=>1,
                         'cash'=>1000,
                         'after_cash'=>$user_info->integral - 1000,
                         'commission'=>0,
                         'status'=>1,
                         'user_id'=>$user_id];
            $fina = FinaIntegralRegRecordRepository::getInstance();
            $res = $fina->createFina($fina_set,$user_id);//生成扣款记录
            if(!$res)
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '复消失败，服务内部异常',
                ]);
            }

            $couponUser = CouponUserRepository::getInstance();
            $set = ['amount'=>1000,
                    'expire_time'=>date("Y-m-d H:i:s",strtotime("+30 day")),
                    'user_id'=>$user_id,
                    'status'=>0
            ];
            $id = $couponUser->createCoupon($set);//生成购物券
            if(!$id)
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '复消失败，服务内部异常',
                ]);
            }
            if($user_info->repeated_consumption_date < date("Y-m-d"))
            {
                $expiry_time = date("Y-m-d",strtotime("+30 day"));
            }
            else
            {
                $expiry_time = date("Y-m-d",strtotime("+30 day",strtotime($user_info->repeated_consumption_date)));
            }
            $log_repeated = LogRepeatedEliminationRepository::getInstance();
            $data = ['amount'=>1000,'user_id'=>$user_info->id,'expiry_time'=>$expiry_time];
            $res = $log_repeated->addData($data);//新增一条复销记录
            if(!$res)
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '复消失败，服务内部异常',
                ]);
            }

            $res = $user->updateUser(['repeated_consumption_date'=>$expiry_time],$user_info->id);//更新复销日期
            if(!$res)
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '复消失败，服务内部异常',
                ]);
            }

            //返回被扣除的业绩 @todo

        }
        else
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '复消失败，未达复消条件',
            ]);
        }
        DB::commit();
        return apiResponse();
    }
}
